package com.tjetc.controller;

import com.tjetc.common.JsonResult;
import com.tjetc.entity.Travelogue;
import com.tjetc.service.TravelogueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("travelogue")
public class TravelogueController {

    @Autowired
    private TravelogueService travelogueService;

    @RequestMapping("all")
    public JsonResult findAll(@RequestParam(name = "is_editor",required = false) Long is_editor ) {
        return travelogueService.findAll(is_editor);
    }
    @RequestMapping("top/{length}")
    public JsonResult getTravelogues(@PathVariable("length")Integer l) {return travelogueService.getTravelogues(l);}

    @RequestMapping("{id}")
    public JsonResult findById(@PathVariable("id") Long travelogueId) {
        return travelogueService.findById(travelogueId);
    }

    @PostMapping("add")
    public JsonResult add(@RequestBody Travelogue travelogue) {
        System.out.println("接收到的easyText: " + travelogue.getEasyText());
        System.out.println("接收到的easyText: " + travelogue.getEasyText());
        System.out.println("接收到的easyText: " + travelogue.getEasyText());
        travelogue.setEasyText(travelogue.getEasyText());
        return travelogueService.addTravelogue(travelogue);
    }
    @PostMapping("/create")
    public JsonResult createTravelogue(@RequestBody Travelogue travelogue) {
        return travelogueService.createNewTravelogue(travelogue);
    }
    /**
     * Add a new travelogue
     * @param travelogue The travelogue to be added
     * @return Response with success or failure message
     */
    @PostMapping("/addNew")
    public ResponseEntity<?> addNewTravelogue(@RequestBody Travelogue travelogue) {
        boolean success = travelogueService.addNewTravelogue(travelogue);
        if (success) {
            return ResponseEntity.ok().body("Travelogue added successfully");
        } else {
            return ResponseEntity.badRequest().body("Failed to add travelogue");
        }
    }


    @PutMapping("update")
    public JsonResult update(@RequestBody Travelogue travelogue) {
        return travelogueService.updateTravelogue(travelogue);
    }


    @DeleteMapping("delete/{id}")
    public JsonResult delete(@PathVariable("id") Long travelogueId) {
        return travelogueService.deleteById(travelogueId);
    }

    /**
     * 查询游记及其作者信息
     * @param travelogueId 游记ID
     * @return 包含作者信息的游记
     */
    @GetMapping("/article/{id}")
    public JsonResult getArticleWithAuthor(@PathVariable("id") Long travelogueId) {
        return travelogueService.findArticleWithAuthorById(travelogueId);
    }
}
